<template>
  <!--  查询 -->
  <div>
    <el-input placeholder="请输入客户姓名" style="width:200px" v-model="queryName"></el-input>
    <el-button @click="queryByName" type="success" plain>查询</el-button>
    <el-button @click="shownurserecordDialog" type="primary" style="width: 100px; margin-left: 50px;font-weight: bolder; font-size: 16px">
      记 录&emsp;
    </el-button>
  </div>
  <!--  显示所有护理信息 table自动循环-->
  <div>{{errorMessage}}</div>
  <el-table :data="nurserRecordList">
    <el-table-column label="序号" type="index" width="80px"></el-table-column>
    <el-table-column prop="customer.customerName" label="客户姓名" width="100px"></el-table-column>
    <el-table-column prop="nursingContent" label="护理名称" width="200px"></el-table-column>
    <el-table-column prop="nursingTime" label="护理时间" width="150px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="nursingCount" label="护理数量" width="80px"></el-table-column>
    <el-table-column prop="user.nickname" label="护理人员" width="100px"></el-table-column>


    <el-table-column  label="操作">
      <template #default="scope">
        <el-button type="primary" @click="showEditDialog(scope.row.id)">修改</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="example-pagination-block">
    <el-pagination background
                   v-model:current-page="pageContains.pageNum"
                   v-model:page-size="pageContains.pageSize"
                   :page-sizes="[10,20,30,50,100]"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="pageContains.total"
                   @size-change="handleSizeChange"
                   @current-change="handlePageChange"
    />
  </div>



  <!--  护理记录对话框 -->
  <el-dialog v-model="nurserecordDialog" :title="dialogTitle">
    <el-form :model="curRecord">


      <el-form-item label="客户姓名">
        <el-col :span="11">
          <el-select v-model="curRecord.customer.customerName" :disabled="dialogTitle === '护理记录信息修改'">
            <el-option
                v-for="cutomer in customerOptions"

                :key="cutomer.id"
                :label="cutomer.customerName"
                :value="cutomer.customerName"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>

      <el-form-item label="护理等级">
        <el-col :span="11">

          <el-select v-model="curLevelName" placeholder="需编辑护理名称前选择（可选）">
            <el-option
                v-for="level in levelOptions"

                :key="level.id"
                :label="level.levelName"
                :value="level.levelName"
            >
            </el-option>
          </el-select>

        </el-col>
      </el-form-item>

      <el-form-item label="护理名称">
        <el-col :span="11">

          <el-select v-model="curRecord.nursingContent">
            <el-option
                v-for="nursing in nursingOptions"

                :key="nursing.id"
                :label="nursing.nursingName"
                :value="nursing.nursingName"
            >
            </el-option>
          </el-select>

        </el-col>
      </el-form-item>

      <el-form-item label="护理时间" >
        <el-col :span="11">
          <el-date-picker v-model="curRecord.nursingTime" type="datetime"></el-date-picker>
        </el-col>
      </el-form-item>

      <el-form-item label="护理数量">
        <el-col :span="11">
          <el-input v-model="curRecord.nursingCount"></el-input>
        </el-col>
      </el-form-item>

      <el-form-item label="护理人员">
        <el-col :span="11">

          <el-select v-model="curRecord.user.nickname">
            <el-option
                v-for="user in userOptions"

                :key="user.id"
                :label="user.nickname"
                :value="user.nickname"
            >
            </el-option>
          </el-select>

        </el-col>
      </el-form-item>


    </el-form>
    <el-button @click="optOne()">{{buttonOpt}}</el-button>
  </el-dialog>
</template>

<script setup>
import {ref, onMounted, reactive, watch} from "vue";
import http from '@/axios/http';
import qs from "qs";
import { useRoute } from 'vue-router'

const route = useRoute()
const nursingName = ref('')
// 存放护理记录数据集合
let nurserRecordList = ref([]);

//报错提示
let errorMessage = ref("")

//模糊查询绑定的 客户名称
let queryName = ref("")

//对话框显示控制
let nurserecordDialog = ref(false)

//客户信息，或者编辑已有客户的 绑定数据
let curRecord = ref({
  customer: {
    customerName: ""
  },
  user: {
    nickname: ""
  },
});

//记录当前选中的护理内容的等级名称
let curLevelName = ref("");

//登记、修改客户信息弹出框的 标题和操作按钮  显示文字
let dialogTitle = ref("");
let buttonOpt = ref("");

//对话框操作类型：1：添加 2：编辑
let dialogOptType = reactive(1);
let size = 10; //当前显示多少行
let pageNum = 1; // 当前页码
let pageSize = 10; //每页显示行数

//当前页码信息
let pageContains = ref({})


//绑定下拉框数据
let customerOptions = ref({})
let userOptions = ref({});
let nursingOptions = ref({});
let levelOptions = ref({});


//根据客户姓名模糊查询护理记录信息
function queryByName(){

  let param = {
    customer: {
      customerName: queryName.value
    }
  }

  http.post('/lyy/get_record_by', param).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 nurserRecordList
        if(result.result === 'success'){
          nurserRecordList.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )
}


function shownurserecordDialog(){
  // 查询要修改的数据后，清空数据
  curRecord.value = {
    customer: {
      customerName: ""
    },
    user: {
      nickname: ""
    },

  };
  curLevelName.value = "";

  //获取下拉框关联的数据
  getRelateData();

  dialogTitle.value = "护理记录录入";
  buttonOpt.value = "录入";

  //弹出客户信息对话框
  nurserecordDialog.value = true;
  dialogOptType = 1 //设置当前操作类型标志是 录入

}

//关闭客户信息对话框
function closenurserecordDialog(){
  nurserecordDialog.value = false;
}

//页面初始化
onMounted(
    ()=>{
      init();
    }
)

function getRecordsByNursingName() {
  const param = { nursingName: nursingName.value }

  http.post('/lyy/get_records_by_nursingname', qs.stringify(param), {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }).then((res) => {
    let result = res.data
    if(result.result === 'success') {
      nurserRecordList.value = result.data
    } else {
      errorMessage.value = result.error || "获取数据失败"
    }
  }).catch(err => {
    errorMessage.value = "请求失败：" + err.message
  })
}

// 监听路由参数变化
watch(() => route.query.nursingName, (newVal) => {
  nursingName.value = newVal || ''
  if (newVal) {
    getRecordsByNursingName()
  } else {
    getAllrecords()
  }
})


function init(){
  //查询所有护理记录信息
  nursingName.value = route.query.nursingName || ''
  if (nursingName.value) {
    getRecordsByNursingName()
  } else {
    getAllrecords()
  }
  //查询需要的字典（{标志1: 值1, 标志2: 值2}）
  //用的时候取 字典[字段值（字典标志）]
}


function getAllrecords(){
  let params = ref({
    size: size,
    pageNum: pageNum,
    pageSize: pageSize
  })

  http.post('/lyy/get_all_records', params.value).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 nurserRecordList
        if(result.result === 'success'){
          pageContains.value = result.data;
          //pageContains.list = null;
          nurserRecordList.value = result.data.list;

        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

//格式化日期
function formatDate(row, column){
  let data = row[column.property];

  if(data == null){
    return null;
  }

  let dt = new Date(data);
  // 补零函数
  const padZero = num => (num < 10 ? '0' + num : num);

  return dt.getFullYear() + '-' +
      padZero(dt.getMonth() + 1) + '-' +
      padZero(dt.getDate()) + ' ' +
      padZero(dt.getHours()) + ':' +
      padZero(dt.getMinutes()) + ':' +
      padZero(dt.getSeconds());
}

function recordOne(){
  let param = curRecord.value;
  http.post('/lyy/add_one_record', param).then(
      (res)=>{
        let result = res.data;
        if(result.result === 'success'){
          //关闭对话框
          closenurserecordDialog()

          //刷新客户列表
          getAllrecords();
        } else {
          errorMessage.value = result.error;
        }

      }
  )
}


//显示编辑对话框
function showEditDialog(nurserecordid){
  //根据id查询记录信息
  getRecordInfo(nurserecordid)

  getRelateData(nurserecordid);

  //显示对话框
  nurserecordDialog.value = true;
  dialogTitle.value = "护理记录信息修改";
  buttonOpt.value = "修改";
  dialogOptType = 2; //设置当前操作类型标志是 修改

  curLevelName.value = "";
}


//获取下拉框关联的数据
function getRelateData(){
  http.post('/lyy/get_all_customername').then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 customerOptions
        if(result.result === 'success'){
          customerOptions.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )
  http.post('/lyy/get_all_nickname').then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 userOptions
        if(result.result === 'success'){
          //选择护理人员，需要过滤掉系统管理员
          userOptions.value = result.data.filter(user => user.nickname !== 'admin');
        } else {
          errorMessage.value = result.error;
        }

      }
  )
  http.post('/lyy/get_all_nursingname').then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 nursingOptions
        if(result.result === 'success'){
          nursingOptions.value = result.data;
        } else {
          errorMessage.value = result.error;
        }
      }
  )
  http.post('/lyy/get_all_levelname').then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 levelOptions
        if(result.result === 'success'){
          levelOptions.value = result.data;
        } else {
          errorMessage.value = result.error;
        }
      }
  )

}


function getRecordInfo(nurserecordid){
  let param = {
    nurserecordid : nurserecordid
  }
  http.post('/lyy/getrecord_by_id', qs.stringify(param)).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 curRecord
        if(result.result === 'success'){
          curRecord.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )
}


//删除护理记录
// function removeOne(nurserecordid){
//   // 弹出确认对话框
//   if (window.confirm('你确定要删除这条记录吗？')) {
//     let param = {
//       nurserecordid: nurserecordid
//     };
//     http.post('/lyy/removerecord_by_id', qs.stringify(param)).then(
//         (res) => {
//           let result = res.data;
//           if (result.result === 'success') {
//             getAllrecords();
//           } else {
//             errorMessage.value = result.error;
//           }
//         }
//     );
//   }
// }

//修改一条记录
function editOne(){
  let param = curRecord.value;
  http.post('/lyy/modifyrecord_by_id', param).then(
      (res)=>{
        let result = res.data;
        if(result.result === 'success'){
          closenurserecordDialog();
          getAllrecords();
        } else {
          errorMessage.value = result.error;
        }
      }
  )
}

function optOne(){
  if(dialogOptType === 1){
    recordOne()
  } else if(dialogOptType === 2) {
    editOne()
  }
}

//分页处理
const handlePageChange = (pageNum1)=>{
  pageNum = pageNum1
  getAllrecords()
}

const handleSizeChange = (pageSize1)=>{
  pageSize = pageSize1
  getAllrecords()
}

// 监听护理等级变化
watch(curLevelName, (newVal) => {
  //根据等级筛选护理内容
  if (newVal) {

    //传递的参数形式，必须为这种形式
    let param = {
      levelname : newVal
    }
    //根据护理等级改变护理内容选项
    http.post('/lyy/getnursingname_by_levelname',qs.stringify(param)).then(
        (res)=>{
          let result = res.data;
          // 返回结果传给 nursingOptions
          if(result.result === 'success'){
            nursingOptions.value = result.data;
          } else {
            errorMessage.value = result.error;
          }
        }
    )

  }
});

</script>

<style scoped>

</style>